﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Text;

namespace Cid.Models
{
	internal static class Mixins
	{
		public static void AttachModel<T>(this DataContext obj, T entity) where T : Base<T>, INotifyPropertyChanged, INotifyPropertyChanging
		{
			if (entity.IsDeleted && entity.IsNew)
				return;

			if (entity.IsDeleted)
			{
				obj.GetTable<T>().DeleteOnSubmit(entity);
			}

			if (!entity.IsNew && entity.IsModified)
			{
				//entity.Detach();
				using(DataContext context = ContextProxy.CreateNewContext()) {
					context.ObjectTrackingEnabled = false;
					obj.GetTable<T>().Attach(entity, entity.GetOriginalById(entity.UniqueId));
				}
			}
			else if(entity.IsNew)
			{
				obj.GetTable<T>().InsertOnSubmit(entity);
			}
		}

		
	}
}
